<template>
  <div :class="className" :style="{ height: height, width: width }" />
</template>

<script>
import echarts from "echarts";
import resize from "./mixins/resize";

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: "chart",
    },
    width: {
      type: String,
      default: "100%",
    },
    height: {
      type: String,
      default: "100%",
    },
    elecData: {
      type: Object,
      default: {
        lockNum: 0,
        chargeNum: 0,
        fullNum: 0,
        freeNum: 0,
      },
    },
    colorArr: {
      type: Array,
      default: () => {
        return ["#92feb1", "#5b91fe", "#5b6fc5", "#f37178"];
      },
    },
  },
  data() {
    return {
      chart: null,
    };
  },
  watch: {
    elecData: {
      deep: true,
      handler(val) {
        this.setOptions(val);
      },
    },
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart();
    });
  },
  beforeDestroy() {
    if (!this.chart) {
      return;
    }
    this.chart.dispose();
    this.chart = null;
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el);
    },
    setOptions(e) {
      const { lockNum, chargeNum, fullNum, freeNum } = e;
      const { colorArr } = this;
      this.chart.setOption({
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
          },
        },
        grid: {
          top: "20px",
          left: "50px",
          right: "40px",
          bottom: "80px",
        },
        yAxis: {
          type: "category",
          data: ["锁仓", "充电", "充满", "空闲"],
          axisLabel: {
            color: (param, index) => {
              return colorArr[index];
            },
          },
          inverse: true,
          splitLine: {
            show: false,
          },
          formatter: (value) => {
            return "{" + value + "| }\n{value|" + value + "}";
          },
        },
        xAxis: {
          type: "value",
          axisLabel: {
            textStyle: {
              color: "#3689cc",
            },
          },
          splitLine: {
            show: false,
          },
        },
        series: [
          {
            data: [
              {
                value: lockNum || 0,
                itemStyle: {
                  color: "#92feb1",
                },
              },
              {
                value: chargeNum || 0,
                itemStyle: {
                  color: "#5b91fe",
                },
              },
              {
                value: fullNum || 0,
                itemStyle: {
                  color: "#5b6fc5",
                },
              },
              {
                value: freeNum || 0,
                itemStyle: {
                  color: "#f37178",
                },
              },
            ],
            type: "bar",
          },
        ],
      });
    },
  },
};
</script>
